﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using JustinAngel.Neurons.Framework;
using JustinAngel.Neurons.Framework.Navigation;
using JustinAngel.UnitedNationsNews.AppCore;
using JustinAngel.UnitedNationsNews.Framework;
using JustinAngel.UnitedNationsNews.Framework.Helpers;
using JustinAngel.UnitedNationsNews.ItemViewMoels;
using JustinAngel.UnitedNationsNews.ServerModel;
using JustinAngel.UnitedNationsNews.Services;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Media;
using Ninject;
using ResumeMusicPlayTest;

namespace JustinAngel.UnitedNationsNews.Pages.Main
{
    public class MainPageViewModel : VViewModelBase
    {
        public MainPageViewModel()
        {
            WithRootModel(WithFirstRootModel);
            MessengerInstance.Register<RootModelChangedMessage>(this, OnRootModelChanged);

            InitSplashScreenVideo();
        }


        private void OnRootModelChanged(RootModelChangedMessage obj)
        {
            if (_wasInitialized)
            {
                BeginInvokeOnUIThread(() => CheckEachCollectionAndAddUpdates(obj));
            }
        }

        private void CheckEachCollectionAndAddUpdates(RootModelChangedMessage msg)
        {
            IsLoading = true;

            var firstPhoto = msg.Content.Photos.FirstOrDefault();
            if (firstPhoto != null && (TopPhotoViewModel == null || firstPhoto.Title != TopPhotoViewModel.Title))
            {
                TopPhotoViewModel = firstPhoto;
            }

            foreach (var NewItem in msg.Content.Latest.Where(l => !TopStoriesViewModels.Any(t => t.Title == l.Title)))
            {
                TopStoriesViewModels.Insert(0, NewItem);
            }

            foreach (var NewItem in msg.Content.Radio.Where(l => !RadioViewModels.Any(t => t.Title == l.Title)))
            {
                RadioViewModels.Insert(0, NewItem);
            }

            foreach (var NewItem in msg.Content.Videos.Where(l => !VideoViewModels.Any(t => t.Title == l.Title)))
            {
                VideoViewModels.Insert(0, NewItem);
            }

            IsLoading = false;
        }

        private bool _wasInitialized = false;
        private void WithFirstRootModel(RootModel obj)
        {
            _wasInitialized = true;

            TopPhotoViewModel = obj.Photos.FirstOrDefault();
            RadioViewModels = obj.Radio.ToObservableCollection();
            TopStoriesViewModels = obj.Latest.ToObservableCollection();
            VideoViewModels = obj.Videos.ToObservableCollection();

            UpdateUIThreadWithCollections();
        }

        private void UpdateUIThreadWithCollections()
        {
            BeginInvokeOnUIThread(() =>
            {
                RaisePropertyChanged(() => TopPhotoViewModel);
                RaisePropertyChanged(() => RadioViewModels);
                RaisePropertyChanged(() => TopStoriesViewModels);
                RaisePropertyChanged(() => VideoViewModels);
                IsLoading = false;
                _isNeedToSetIsLoadingToFalse = !IsAttachedToViewAsDataContext;
                DispatcherTimerHelper.OnWithDispatcher(TimeSpan.FromSeconds(3), () =>
                {
                    if (IsSplashVisible && this.SplashScreenMediaSource == null)
                        IsSplashVisible = false;
                });
            });
        }

        public PhotoItemViewModel TopPhotoViewModel { get; set; }
        public ObservableCollection<RadioItemViewModel> RadioViewModels { get; set; }
        public ObservableCollection<ArticleItemViewModel> TopStoriesViewModels { get; set; }
        public ObservableCollection<VideoItemViewModel> VideoViewModels { get; set; }

        private bool _isLoading;
        public bool IsLoading
        {
            get { return _isLoading; }
            set
            {
                _isLoading = value;
                RaisePropertyChangedAndUpdateVSM(() => IsLoading, value);
            }
        }

        private List<SectionViewModel> _sections;
        public List<SectionViewModel> Sections
        {
            get
            {
                if (_sections == null)
                {
                    _sections = new List<SectionViewModel>()
                    {
                            new SectionViewModel("Health, Poverty, Food Security", "health"),            
                            new SectionViewModel("United Nations Affairs", "unaffairs"), 
                            new SectionViewModel("Human Rights", "humanrights"),
                            new SectionViewModel("Law, Crime Prevention", "law"),    
                            new SectionViewModel("Environment, Shelter", "environment"),
                            new SectionViewModel("Culture, Education", "edculture"),
                            new SectionViewModel("Economic Development", "econdev"),
                            new SectionViewModel("Women, Kids, Population", "wcp", "Women, Children, and Population"),
                            new SectionViewModel("Peace and Security", "peacesecurity"),
                            new SectionViewModel("Middle East", "mideast"),
                            new SectionViewModel("Africa", "africa"),
                            new SectionViewModel("Europe", "europe"),
                            new SectionViewModel("Americas", "americas"),
                            new SectionViewModel("Asia Pacific", "asiapac"),
                    };
                }
                return _sections;
            }
            set { _sections = value; }
        }

        public IEnumerable<SectionViewModel> FirstColumnSections
        {
            get { return Sections.Take(7); }
        }

        public IEnumerable<SectionViewModel> SecondColumnSections
        {
            get { return Sections.Skip(7).Take(7); }
        }


        #region Splash Screen
        private Uri _splashScreenMediaSource;
        public Uri SplashScreenMediaSource
        {
            get { return _splashScreenMediaSource; }
            set
            {
                _splashScreenMediaSource = value;
                RaisePropertyChanged(() => SplashScreenMediaSource);
            }
        }

        private bool _isSplashVisible = true;
        public bool IsSplashVisible
        {
            get { return _isSplashVisible; }
            set
            {
                _isSplashVisible = value;
                RaisePropertyChangedAndUpdateVSM(() => IsSplashVisible, value);
            }
        }

        public MediaElementState SplashMediaState { get; set; }

        private void InitSplashScreenVideo()
        {

            if (!Services.DataService.HasCachedWebRequestResult)
            {
                this.SplashScreenMediaSource = new Uri("/UNNews.wmv", UriKind.Relative);
            }
        }


        public ICommand SplashMediaStateChanged
        {
            get
            {
                return new RelayCommand(() =>
                {
                    if (SplashMediaState == MediaElementState.Playing)
                    {
                        ShowSplashVideo();
                    }
                });
            }
        }

        public void ShowSplashVideo()
        {
            IsPlayingSplashOverlayAnimation = true;
            DispatcherTimerHelper.On(TimeSpan.FromSeconds(11), () =>    
            {
                IsSplashVisible = false;
                IsPlayingSplashOverlayAnimation = false;
                DispatcherTimerHelper.On(TimeSpan.FromSeconds(5), () =>
                {
                    SplashScreenMediaSource = null;
                    //try
                    //{
                    //    MediaPlayer.Resume();
                    //    FrameworkDispatcher.Update();
                    //}
                    //catch (Exception ex)
                    //{
                    //    // mothafucka, I have to have a try-catch block otherwise this doesn't actually work
                    //    // fucking XNA. 
                    //}
                    XnaMusicUtil.RestoreCurrentMediaState();
                });
            });
        }

        private bool _isPlayingSplashOverlayAnimation;
        public bool IsPlayingSplashOverlayAnimation
        {
            get { return _isPlayingSplashOverlayAnimation; }
            set
            {
                _isPlayingSplashOverlayAnimation = value;
                RaisePropertyChangedAndUpdateVSM(() => IsPlayingSplashOverlayAnimation, value);
            }
        }

        #endregion Splash Screen

        public ICommand NavigateToPhotosPage
        {
            get
            {
                return new RelayCommand(() =>
                    DispatcherTimerHelper.On(TimeSpan.FromMilliseconds(256), () => // let tilt finish
                        MessengerInstance.Send(new NavigateToMessage(PageSources.PhotosPage))
                ));
            }
        }

        public void LoadHistoryOrNowPlayingTileClick(ZuneHistoryItem result)
        {
            if (result != null)
            {
                if (result.Tag == "IsRadio")
                {
                    MessengerInstance.Send(new NavigateToMessage(PageSources.VideoPage,
                        new RadioItemViewModel()
                        {
                            Mp3Uri = new Uri(result.Source, UriKind.Absolute),
                            Title = result.Title,
                            IsNowPlayingRestore = result.IsNowPlayingRestore,
                            IsHistoryTileRestore = !result.IsNowPlayingRestore
                        }));

                }
                else if (result.Tag == "IsVideo")
                {
                    //MessageBox.Show("Source: " + result.Source + Environment.NewLine + "Title: " + result.Title + Environment.NewLine + "Restore: " + result.IsNowPlayingRestore);
                    MessengerInstance.Send(new NavigateToMessage(PageSources.VideoPage,
                        new VideoItemViewModel()
                        {
                            YouTubeUrl = new Uri(result.Source, UriKind.Absolute),
                            Title = result.Title,
                            IsNowPlayingRestore = result.IsNowPlayingRestore,
                            IsHistoryTileRestore = !result.IsNowPlayingRestore
                        }));
                }
            }

        }

        public bool _isNeedToSetIsLoadingToFalse = false;

        public override void OnAfterAttachedToViewAsDataContext()
        {
            base.OnAfterAttachedToViewAsDataContext();

            if (_isNeedToSetIsLoadingToFalse)
            {
                IsLoading = false;
                _isNeedToSetIsLoadingToFalse = false; 
            }
        }
    }
}
